import requests
import socket
import time
import random

from python_depend.time_urtils import get_current_time

WORK_FLOW_API_URL = "http://agent-robot-engine-server-stable:9090/api/pipeline/v1/chat"
WORK_FLOW_CACHE_API_URL = "http://ai-content-hub:8080/aicontent/v1"


def get_local_ip() -> str:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception:
        return "127.0.0.1"


def generate_session_id() -> str:
    return str(int(time.time() * 1000)) + str(random.randint(1000, 9999))


def generate_headers(session_id: str) -> dict:
    local_ip = get_local_ip()
    trace_id = str(int(time.time() * 1000)) + str(random.randint(100, 999))

    headers = {
        "Content-Type": "application/json",
        "X-Remote-Ip": local_ip,
        "X-Remote-Svc": "dolphinscheduler",
        "X-Session-Id": session_id,  # 这里用 session_id
        "X-Trace-Id": trace_id,
        "X-User-Id": trace_id,
    }
    return headers



# 工作流直接调用调用
def work_flow_call(pipe_name: str, input_variable_value: dict):
    session_id = generate_session_id()
    headers = generate_headers(session_id)
    payload = {
        "pipe_name": pipe_name,
        "mode": "WORK_FLOW",
        "input_variable_value": input_variable_value
    }
    start_time = time.time()  # 记录开始时间
    try:
        response = requests.post(url=WORK_FLOW_API_URL, json=payload, headers=headers, timeout=300)
        elapsed_time = time.time() - start_time
        print(
            f"请求url:{WORK_FLOW_API_URL},请求状态：{response.status_code},请求参数：{payload} ,请求耗时: {elapsed_time:.4f} 秒")
        response.raise_for_status()  # 检查请求是否成功（状态码 200）
        result_data = response.json()
        if result_data.get("status_code") != 200:
            print(f"接口调用失败: {result_data.get('status_msg', '无错误信息')}")
            return None
        return result_data
    except Exception as e:
        print("HTTP请求异常:", e)


# 缓存层调用
def work_flow_cache_call(pipe_name: str, input_variable_value: dict):
    headers = {
        "Content-Type": "application/json"
    }
    payload = {
        "workflow_id": pipe_name,
        "input_variable_values": input_variable_value
    }
    start_time = time.time()  # 记录开始时间
    url = WORK_FLOW_CACHE_API_URL + "/sync_query"

    try:
        response = requests.post(url=url, json=payload, headers=headers, timeout=300)
        elapsed_time = time.time() - start_time
        print(
            f"请求url:{url},请求状态：{response.status_code},请求参数：{payload} ,请求耗时: {elapsed_time:.4f} 秒")
        response.raise_for_status()  # 检查请求是否成功（状态码 200）
        result_data = response.json()
        if result_data.get("status_code") != 0:
            print(f"接口调用失败: {result_data.get('status_msg', '无错误信息')}")
            return None
        return result_data
    except Exception as e:
        print("HTTP请求异常:", e)

def work_flow_cache_delete(pipe_name: str, input_variable_value: dict):

    headers = {
        "Content-Type": "application/json"
    }
    payload = {
        "workflow_id": pipe_name,
        "input_variable_values": input_variable_value
    }
    start_time = time.time()  # 记录开始时间
    url = WORK_FLOW_CACHE_API_URL + "/cache_delete"
    try:
        response = requests.post(url=url, json=payload, headers=headers, timeout=300)
        elapsed_time = time.time() - start_time
        print(
            f"请求url:{url},请求状态：{response.status_code},请求参数：{payload} ,请求耗时: {elapsed_time:.4f} 秒")
        response.raise_for_status()  # 检查请求是否成功（状态码 200）
        result_data = response.json()
        if result_data.get("status_code") != 0:
            print(f"接口调用失败: {result_data.get('status_msg', '无错误信息')}")
            return None
        return result_data
    except Exception as e:
        print("HTTP请求异常:", e)


def work_flow_cache_refresh(pipe_name: str, input_variable_value: dict):

    headers = {
        "Content-Type": "application/json"
    }
    payload = {
        "workflow_id": pipe_name,
        "input_variable_values": input_variable_value
    }
    start_time = time.time()  # 记录开始时间
    url = WORK_FLOW_CACHE_API_URL + "/refresh_res"
    try:
        print(f"请求时间:{str(get_current_time())},请求url:{url},请求参数：{payload}")
        response = requests.post(url=url, json=payload, headers=headers, timeout=300)
        elapsed_time = time.time() - start_time
        print(
            f"请求url:{url},请求状态：{response.status_code},请求参数：{payload} ,请求耗时: {elapsed_time:.4f} 秒")
        response.raise_for_status()  # 检查请求是否成功（状态码 200）`
        result_data = response.json()
        if result_data.get("status_code") != 0:
            print(f"接口调用失败: {result_data.get('status_msg', '无错误信息')}")
            return None
        return result_data
    except Exception as e:
        print("HTTP请求异常:", e)